<template>
  <div class="swiper" @mouseover="stop" @mouseleave="play">
    <div
      class="swiper-item"
      v-for="(item, index) in imgs"
      :class="{ fade: active === index }"
    >
      <img :src="item.imgUrl" alt="" />
    </div>
    <div class="swiper_btn prev" @click="prev">&lt;</div>
    <div class="swiper_btn next" @click="next">&gt;</div>
    <div class="swiper_dot">
      <span
        v-for="(item, index) in imgs"
        :key="item.id"
        :class="{ active: active === index }"
        @mouseenter="active = index"
      ></span>
    </div>
  </div>
</template>
<script setup lang="ts">
interface Props {
  autoPlay: boolean;
  duration: number;
}

const props = withDefaults(defineProps<Props>(), {
  autoPlay: false,
  duration: 3000,
});
const active = ref(0);
const imgs = [
  {
    id: "18",
    imgUrl: "https://picsum.photos/800/300?random=1",
  },
  {
    id: "20",
    imgUrl: "https://picsum.photos/800/300?random=2",
  },
  {
    id: "19",
    imgUrl: "https://picsum.photos/800/300?random=3",
  },
  {
    id: "17",
    imgUrl: "https://picsum.photos/800/300?random=4",
  },
  {
    id: "16",
    imgUrl: "https://picsum.photos/800/300?random=5",
  },
];
let timer = null;
const play = () => {
  if (!props.autoPlay) return;
  clearInterval(timer);
  timer = setInterval(() => {
    if (active.value >= imgs.length - 1) {
      active.value = 0;
    } else {
      active.value++;
    }
  }, props.duration);
};
const stop = () => {
  clearInterval(timer);
};
onMounted(() => {
  play();
});
onUnmounted(() => {
  stop();
});
const prev = () => {
  if (active.value <= 0) {
    active.value = imgs.length - 1;
  } else {
    active.value--;
  }
};
const next = () => {
  if (active.value >= imgs.length - 1) {
    active.value = 0;
  } else {
    active.value++;
  }
};
</script>
<style scoped lang="scss">
.swiper {
  width: 80%;
  height: 400px;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  .swiper-item {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    transition: all 0.5s;
  }
  .fade {
    opacity: 1;
  }
  img {
    width: 100%;
    height: 100%;
  }
  .swiper_btn {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    text-align: center;
    line-height: 50px;
    color: #fff;
    cursor: pointer;
  }
  .prev {
    left: 20px;
  }
  .next {
    right: 20px;
  }
  .swiper_dot {
    position: absolute;
    bottom: 20px;
    left: 0;
    text-align: center;
    width: 100%;
    span {
      display: inline-block;
      width: 12px;
      height: 13px;
      background-color: rgba(0, 0, 0, 0.2);
      border-radius: 50%;
      margin: 0 5px;
      cursor: pointer;
      transition: all 0.5s;
      &.active {
        background-color: red;
      }
    }
  }
}
</style>
